package org.zero.onlinesubject.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.zero.onlinesubject.common.constant.RedisConstant;
import org.zero.onlinesubject.entity.Role;
import org.zero.onlinesubject.service.RoleService;
import org.zero.onlinesubject.mapper.RoleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Role getRoleById(Integer id) {
        String json = stringRedisTemplate.opsForValue().get(RedisConstant.ROLE_TYPE_PREFIX + id);
        if(!StringUtils.isNullOrEmpty(json)){
            return JSON.parseObject(json, Role.class);
        }
        Role role = roleMapper.selectById(id);
        if(role!=null) stringRedisTemplate.opsForValue().set(RedisConstant.ROLE_TYPE_PREFIX+id,JSON.toJSONString(role),30, TimeUnit.MINUTES);

        return role;
    }

    @Override
    public List<Role> getRoleList() {
        String json = stringRedisTemplate.opsForValue().get(RedisConstant.ROLE_TYPE_PREFIX + "RoleList");
        if(!StringUtils.isNullOrEmpty(json)){
            return JSON.parseObject(json,new TypeReference<List<Role>>(){});
        }
        List<Role> roleList = roleMapper.selectList(null);
        if(roleList!=null && !roleList.isEmpty())
            stringRedisTemplate.opsForValue().set(RedisConstant.ROLE_TYPE_PREFIX+"RoleList",JSON.toJSONString(roleList),30, TimeUnit.MINUTES);
        return roleList;
    }
}




